package com.cloud.gateway.component;

import com.cloud.gateway.util.RedisUtil;
import org.springframework.http.HttpHeaders;

public class AuthServer {

    //header请求过来值(x-username) 作为 ak
    public String username;

    public String nonce;
    public String date;
    public String signature;

    //密钥约定sk
    public String secretAccessKey;

    public String contentType;


    public AuthServer(String secretAccessKey)
    {
        this.secretAccessKey = secretAccessKey;
    }

    protected void setInfo(HttpHeaders httpHeaders)
    {
       this.username =  httpHeaders.containsKey("x-username")
               ? String.valueOf(httpHeaders.get("x-username").get(0)):"";
       this.nonce = httpHeaders.containsKey("x-nonce")
               ? String.valueOf(httpHeaders.get("x-nonce").get(0)):"";
       this.date = httpHeaders.containsKey("x-date")
               ? String.valueOf(httpHeaders.get("x-date").get(0)):"";
       this.contentType = httpHeaders.containsKey("Content-Type")
               ? String.valueOf(httpHeaders.get("Content-Type").get(0)):"";

       this.signature = httpHeaders.containsKey("x-signature")
               ? String.valueOf(httpHeaders.get("x-signature").get(0)):"";
    }

    public Boolean doAuth(RedisUtil redisUtil, String data, String method, String url, HttpHeaders httpHeaders)
    {
        setInfo(httpHeaders);
        AuthClient authClient = new AuthClient();
        String contentMd5 = authClient.getContentMD5(data);

        //todo 可结合redis进行指定时间nonce唯一性判断, date时间过期判断..自定义
 /*       String keyNonce = this.nonce;
          redis = new Redis();
        if (redis->has($keyNonce)) {
            return false;
        }*/
        String keyNonce = this.nonce;
        if(redisUtil.hasKey(keyNonce)) {
            return false;
        }

        authClient.date = this.date;
        authClient.nonce = this.nonce;
        authClient.accessKey = this.username;
        authClient.contentMD5 = contentMd5;
        authClient.contentType = this.contentType;
        authClient.secretAccessKey = this.secretAccessKey;
        String sign = authClient.genSign(method, url);

        if(sign.equals(this.signature)) {
            //redis->put($keyNonce, nonce, 1);
            redisUtil.set(keyNonce,keyNonce,300);

            return true;
        }else{
            return false;
        }

    }

}
